package com.uls.web.controller.ycl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.uls.common.core.domain.entity.SysUser;
import com.uls.system.service.impl.SysUserServiceImpl;
import com.uls.ycl.domain.*;
import com.uls.ycl.mapper.RepairRequestMapper;
import com.uls.ycl.service.*;
import com.uls.ycl.vo.LineVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.uls.common.annotation.Log;
import com.uls.common.core.controller.BaseController;
import com.uls.common.core.domain.AjaxResult;
import com.uls.common.enums.BusinessType;
import com.uls.common.utils.poi.ExcelUtil;
import com.uls.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import com.uls.framework.config.MinioProp;
import com.uls.framework.utils.MinioUtils;

/**
 * 报修请求Controller
 * 
 * @author ycl
 * @date 2024-11-06
 */
@RestController
@RequestMapping("/ycl/request")
public class RepairRequestController extends BaseController
{
    @Autowired
    private IRepairRequestService repairRequestService;

    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private IRepairAreaService RepairAreaService;
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private MinioProp minioProp;
    @Autowired
    private IRepairEvaluationService repairEvaluationService;
    @Autowired
    private IRepairPersonnelService repairPersonnelService;
    @Autowired
    private IRepairMaterialService repairMaterialService;
    @Autowired
    private RepairRequestMapper repairRequestMapper;

    /**
     * 查询报修请求列表
     */
    @PreAuthorize("@ss.hasPermi('ycl:request:list')")
    @GetMapping("/list")
    public TableDataInfo list(RepairRequest repairRequest)
    {
        startPage();
        List<RepairRequest> list = repairRequestService.selectRepairRequestList(repairRequest);
        //通过外键id找名字
        for(RepairRequest request :list){
            Long userId = request.getUserId();
            Long areaId = request.getAreaId();
            Long personnelId = request.getPersonnelId();
            Long materialId = request.getMaterialId();

            RepairArea repairArea = RepairAreaService.selectRepairAreaByAreaId(areaId);
            SysUser sysUser = sysUserService.selectUserById(userId);
            RepairPersonnel repairPersonnel = repairPersonnelService.selectRepairPersonnelByPersonnelId(personnelId);
            RepairMaterial repairMaterial = repairMaterialService.selectRepairMaterialByMaterialId(materialId);

            if(repairMaterial!=null){
                request.setMname(repairMaterial.getName());
            }
            if(sysUser!=null)
                request.setUserName(sysUser.getUserName());
            if(repairArea!=null)
                request.setAreaName(repairArea.getName());
            if(repairPersonnel!=null)
                request.setName(repairPersonnel.getName());
        }

        return getDataTable(list);
    }

    /**
     * 导出报修请求列表
     */
    @PreAuthorize("@ss.hasPermi('ycl:request:export')")
    @Log(title = "报修请求", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RepairRequest repairRequest)
    {
        List<RepairRequest> list = repairRequestService.selectRepairRequestList(repairRequest);
        ExcelUtil<RepairRequest> util = new ExcelUtil<RepairRequest>(RepairRequest.class);
        util.exportExcel(response, list, "报修请求数据");
    }

    /**
     * 获取报修请求详细信息
     */
    @PreAuthorize("@ss.hasPermi('ycl:request:query')")
    @GetMapping(value = "/{requestId}")
    public AjaxResult getInfo(@PathVariable("requestId") Long requestId)
    {
        return success(repairRequestService.selectRepairRequestByRequestId(requestId));
    }

    /**
     * 新增报修请求
     */
    @PreAuthorize("@ss.hasPermi('ycl:request:add')")
    @Log(title = "报修请求", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RepairRequest repairRequest)
    {
        repairRequest.setUserId(getUserId());
        repairRequest.setCreatedAt(new Date());
/*        //报修评价同时添加
        RepairEvaluation evaluation = new RepairEvaluation();
        evaluation.setRequestId(repairRequest.getRequestId());
        evaluation.setUserId(getUserId());
        repairEvaluationService.insertRepairEvaluation(evaluation);*/



        return toAjax(repairRequestService.insertRepairRequest(repairRequest));
    }

    /**
     * 修改报修请求
     */
    @PreAuthorize("@ss.hasPermi('ycl:request:edit')")
    @Log(title = "报修请求", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RepairRequest repairRequest)
    {
        repairRequest.setUpdatedAt(new Date());

        return toAjax(repairRequestService.updateRepairRequest(repairRequest));
    }

    /**
     * 删除报修请求
     */
    @PreAuthorize("@ss.hasPermi('ycl:request:remove')")
    @Log(title = "报修请求", businessType = BusinessType.DELETE)
	@DeleteMapping("/{requestIds}")
    public AjaxResult remove(@PathVariable Long[] requestIds)
    {
        return toAjax(repairRequestService.deleteRepairRequestByRequestIds(requestIds));
    }

    /**
     * 上传
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/uploadMinio")
    public String uploadMinio(@RequestParam(name = "file", required = false) MultipartFile file, HttpServletRequest request) {
        JSONObject res = null;
        try {
            res = minioUtils.uploadFile(file, minioProp.getBucket());
        } catch (Exception e) {
            e.printStackTrace();
            res.put("code", 0);
            res.put("msg", "上传失败");
        }
        return res.toJSONString();
    }
    @PreAuthorize("@ss.hasPermi('ycl:RepairRequest:down')")
    @PostMapping("/imageDown")
    public  void imageDown(String fileName, HttpServletResponse response){
        minioUtils.download(minioProp.getBucket(),fileName,response);
    }

    /*获取所有用户信息*/
    @GetMapping("/getAllUsers")
    public AjaxResult getAllSchools()
    {
        SysUser user = new SysUser();
        List<SysUser> list = sysUserService.selectUserList(user);
        return success(list);
    }
    @GetMapping("/getAllpersions")
    public AjaxResult getAllSchools1()
    {
        RepairPersonnel personnel = new RepairPersonnel();
        List<RepairPersonnel> list = repairPersonnelService.selectRepairPersonnelList(personnel);
        return success(list);
    }
    @GetMapping("/getAllRequests")
    public AjaxResult getAllSchools2()
    {
        RepairRequest request = new RepairRequest();
        List<RepairRequest> list = repairRequestService.selectRepairRequestList(request);
        return success(list);
    }



    /**
     * 提交报修信息申请
     */
    @PreAuthorize("@ss.hasPermi('ycl:request:resuestSubmit')")
    @Log(title = "报修信息", businessType = BusinessType.EXPORT)
    @GetMapping("/submitRepairRequest/{requestId}")
    public AjaxResult submitStudent(@PathVariable Long requestId)
    {
        return  toAjax(repairRequestService.submit(requestId,getUserId()));
    }

    /**
     * 查询未审批学生信息列表
     */
    @PreAuthorize("@ss.hasPermi('ycl:request:listNo')")
    @Log(title = "报修信息", businessType = BusinessType.EXPORT)
    @GetMapping("/listNo")
    public TableDataInfo listNo(RepairRequest request)
    {
        startPage();
        //List<SysStudent> list = sysStudentService.noFinishTask(getUserId(),"myStudentProcess");//关联工作流没有带条件查询
        List<RepairRequest> list = repairRequestService.noFinishTask(getUserId(),"myrepair",request);//关联工作流带条件查询
        //通过外键id找名字
        for(RepairRequest request1 :list){
            Long userId = request1.getUserId();
            Long areaId = request1.getAreaId();
            Long personnelId = request1.getPersonnelId();

            RepairPersonnel repairPersonnel = repairPersonnelService.selectRepairPersonnelByPersonnelId(personnelId);
            RepairArea yclRepairArea = RepairAreaService.selectRepairAreaByAreaId(areaId);
            SysUser sysUser = sysUserService.selectUserById(userId);

            Long materialId = request1.getMaterialId();
            RepairMaterial repairMaterial = repairMaterialService.selectRepairMaterialByMaterialId(materialId);
            if(repairMaterial!=null){
                request1.setMname(repairMaterial.getName());
            }

            if(sysUser!=null)
                request1.setUserName(sysUser.getUserName());
            if(yclRepairArea!=null)
                request1.setAreaName(yclRepairArea.getName());
            if(repairPersonnel!=null)
                request1.setName(repairPersonnel.getName());
        }

        return getDataTable(list);

    }



    /*获取学生详细信息*/
    @GetMapping("/getRepaireRequestComment/{requestId}")
    public AjaxResult getStudentInfo(@PathVariable("requestId") Long requestId)
    {
        RepairRequest request = repairRequestService.selectRepairRequestByRequestId(requestId);

        request.setTaskCommentVoList(repairRequestService.getTaskCommentList(request.getFlowInstantId()));  //找出前面审批人的审批信息
        return AjaxResult.success(request);
    }


    //edu:request:editnoapprove
    /*查询未审批的学生列表，审批*/
    @PreAuthorize("@ss.hasPermi('ycl:request:editnoapprove')")
    @Log(title = "查询未审批的报修信息列表", businessType = BusinessType.EXPORT)
    @PostMapping("/editnoapprove")
    public AjaxResult editStudentNoApprove(@RequestBody RepairRequest request){

        request.setUpdatedAt(new Date());
        repairRequestService.updateRepairRequest(request);//审批同时可以修改数据

        repairRequestService.completeTask(request.getFlowInstantId(),request.getAgree(),getUserId(),request.getComment(),request.getRequestId());
        return toAjax(200);
    }




    /**
     * 查询已审批学生信息列表
     */
    @PreAuthorize("@ss.hasPermi('ycl:request:listFinished')")
    @Log(title = "报修信息", businessType = BusinessType.EXPORT)
    @GetMapping("/listFinished")
    public TableDataInfo listFinished(RepairRequest request)
    {


        startPage();
        //List<SysStudent> list = sysStudentService.noFinishTask(getUserId(),"myStudentProcess");//关联工作流没有带条件查询
        List<RepairRequest> list = repairRequestService.finishedTask(getUserId(),"myrepair",request);//关联工作流带条件查询
        //通过外键id找名字
        for(RepairRequest request1 :list){
            Long userId = request1.getUserId();
            Long areaId = request1.getAreaId();
            Long personnelId = request1.getPersonnelId();
            RepairArea RepairArea = RepairAreaService.selectRepairAreaByAreaId(areaId);
            SysUser sysUser = sysUserService.selectUserById(userId);
            RepairPersonnel repairPersonnel = repairPersonnelService.selectRepairPersonnelByPersonnelId(personnelId);

            Long materialId = request1.getMaterialId();
            RepairMaterial repairMaterial = repairMaterialService.selectRepairMaterialByMaterialId(materialId);
            if(repairMaterial!=null){
                request1.setMname(repairMaterial.getName());
            }

            if(sysUser!=null)
                request1.setUserName(sysUser.getUserName());
            if(RepairArea!=null)
                request1.setAreaName(RepairArea.getName());
            if(repairPersonnel!=null)
                request1.setName(repairPersonnel.getName());
        }
        return getDataTable(list);


    }

//报表
@GetMapping("/zhu")
public AjaxResult Line() {
    List<LineVo> list = repairRequestMapper.selectLineVo();
    //System.out.println("从数据库获取的数据: " + list); // 添加日志记录

    ArrayList<LineVo> result = new ArrayList<>();
    for (LineVo lineVo : list) {
        LineVo lineVo1 = new LineVo();
        lineVo1.setName(lineVo.getName());
        lineVo1.setTotal(lineVo.getTotal());
        result.add(lineVo1);
    }

/*    for (LineVo lineVo2 : result) {
        System.out.println("柱状图数据=== " + lineVo2.getName() + "  " + lineVo2.getTotal());
    }*/

    return AjaxResult.success(result);
}









}
